import { Nohm, NohmModel, TTypedDefinitions, timestampProperty } from 'nohm';
import { redisClient } from '../util/redis';
import { Config } from '../app';

export const OrderStatus = {
	PLACED: 'placed',
	FINISH: 'finish',
	CANCEL: 'cancel',
};

export const orderModel = Nohm.model('order', {
	properties: {
		createTime: {
			type: 'number',
			validations: ['notEmpty'],
		},
		createTimeSec: {
			type: 'number',
			index: true,
			validations: ['notEmpty'],
		},
		userId: {
			type: 'string',
			index: true,
			validations: ['notEmpty'],
		},
		basePrice: {
			type: 'number',
			validations: ['notEmpty'],
		},
		target: {
			type: 'string',
			validations: ['notEmpty'],
		},
		status: {
			type: 'string',
			defaultValue: 'placed',
			validations: ['notEmpty'],
		},
		amount: {
			defaultValue: 0,
			type: 'number',
		},
		charge: {
			defaultValue: 0,
			type: 'number',
		},
		result: {
			defaultValue: 0,
			type: 'number',
		},
	},
});

export let getOrderByTime = async (timeSec: number, raw = false) => {
	let os = await orderModel.findAndLoad({ createTimeSec: timeSec });
	if (raw) {
		return os.map((v, k) => {
			return v.allProperties();
		});
	} else {
		return os;
	}
};

export let getOpenedOrders = async function() {
	return await new Promise<any[]>(fill => {
		let key = Config.getRedisNohmPrefix() + ':openOrders';
		redisClient.lrange(key, 0, -1, async (err, res: string[]) => {
			let orders = await orderModel.loadMany(res);
			let props = orders.map(v => {
				return v.allProperties();
			});
			fill(props);
		});
	});
};

export let openOrder = async function(order) {
	console.log('open order', order.id);
	let key = Config.getRedisNohmPrefix() + ':openOrders';
	redisClient.rpush(key, order.id);
};

export let closeOrder = async function(orderId, price) {
	console.log('close order', orderId);
	let order = await orderModel.load(orderId);
	let key = Config.getRedisNohmPrefix() + ':openOrders';
	order.property('status', OrderStatus.FINISH);
	await order.save();
	redisClient.lrem(key, 1, orderId);

	key = Config.getRedisNohmPrefix() + ':checkAccounts';
	redisClient.rpush(
		key,
		JSON.stringify({
			userId: order.property('userId'),
			orderId,
			result: order.property('amount'),
		}),
	);
};

export let cancelOrder = async function(orderId) {
	console.log('cancel order', orderId);
	let order = await orderModel.load(orderId);
	let key = Config.getRedisNohmPrefix() + ':openOrders';
	order.property('status', OrderStatus.CANCEL);
	await order.save();
	redisClient.lrem(key, 1, orderId);
};
